#ifdef WIN32
#pragma warning (disable: 4996 4267)
#include <windows.h>
#endif

#include <string.h>
#include <stdlib.h>

#include "ncrypt_string.h"
#include "nmalloc.h"

void streverse(const char* src, char* dst)
{
	int len = strlen(src);
	int half = (len-1) / 2;
	for ( int i = 0 ; i <= half ; i++ )
	{
		int ri = len - i - 1;
		char tmp = src[i];
		dst[i] = src[ri];
		dst[ri] = tmp;
	}
	dst[len] = 0;
}

#ifdef WIN32
void wcreverse(const wchar_t* src, wchar_t* dst)
{
	int len = wcslen(src);
	int half = (len-1) / 2;
	for ( int i = 0 ; i <= half ; i++ )
	{
		int ri = len - i - 1;
		wchar_t tmp = src[i];
		dst[i] = src[ri];
		dst[ri] = tmp;
	}
	dst[len] = 0;
}
#endif

int strevncmp(const char* s1, const char* s2, int len)
{
	char* t1 = strdup(s1);
	char* t2 = strdup(s2);
	streverse(t1, t1);
	streverse(t2, t2);
	int ret = strncmp(t1, t2, len);
	free(t1);
	free(t2);
	return ret;
}

#ifdef WIN32
int wcrevncmp(const wchar_t* s1, const wchar_t* s2, int len)
{
	wchar_t* t1 = wcsdup(s1);
	wchar_t* t2 = wcsdup(s2);
	wcreverse(t1, t1);
	wcreverse(t2, t2);
	int ret = wcsncmp(t1, t2, len);
	free(t1);
	free(t2);
	return ret;
}
#endif // WIN32

#if defined(__APPLE__) && defined(__MACH__)
char* strndup(const char* src, int len)
{
	int copylen = strlen(src);
	if ( copylen > len )
		copylen = len;
	char* dst = (char*)malloc(copylen+1);
	memcpy(dst, src, copylen);
	dst[copylen] = 0;
	return dst;
}
#endif // __APPLE__ && __MACH__
